package com.weiter.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiter.common.core.constant.CacheConstants;
import com.weiter.common.core.constant.UserConstants;
import com.weiter.common.core.core.page.PageQuery;
import com.weiter.common.core.core.text.Convert;
import com.weiter.common.core.exception.ServiceException;
import com.weiter.common.core.service.SysConfigApiService;
import com.weiter.common.core.utils.StringUtils;
import com.weiter.common.datasource.annotation.DataSource;
import com.weiter.common.datasource.enums.DataSourceType;
import com.weiter.common.redis.service.RedisService;
import com.weiter.system.domain.SysConfig;
import com.weiter.system.mapper.SysConfigMapper;
import com.weiter.system.service.ISysConfigService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 参数配置
 * @author weiter
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService, SysConfigApiService {

    @Resource
    private SysConfigMapper configMapper;

    @Resource
    private RedisService redisService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置分页列表
     * @param query     参数配置信息
     * @param pageQuery 分页查询信息
     * @return 参数配置分页列表
     */
    @Override
    public Page<SysConfig> selectSysConfigPage(SysConfig query, PageQuery pageQuery) {
        LambdaQueryWrapper<SysConfig> lqw = buildQueryWrapper(query);
        return baseMapper.selectPage(pageQuery.build(), lqw);
    }

    /**
     * 查询参数配置列表
     * @param sysConfig 参数配置信息
     * @return 参数配置列表
     */
    @Override
    public List<SysConfig> selectSysConfigList(SysConfig sysConfig) {
        LambdaQueryWrapper<SysConfig> lqw = buildQueryWrapper(sysConfig);
        return baseMapper.selectList(lqw);
    }

    /**
     * 查询参数配置详情
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public SysConfig selectConfigById(Long configId) {
        SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectById(config);
    }

    /**
     * 查询参数键值
     * @param configKey 参数键名
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        return selectConfigByKeyPublic(configKey);
    }

    /**
     * 新增参数配置
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        int row = configMapper.insert(config);
        if (row > 0) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        SysConfig temp = configMapper.selectById(config.getConfigId());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
            redisService.deleteObject(getCacheKey(temp.getConfigKey()));
        }

        int row = configMapper.updateById(config);
        if (row > 0) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteById(configId);
            redisService.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = configMapper.selectList(new LambdaQueryWrapper<>());
        for (SysConfig config : configsList) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否重复
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyDuplicate(SysConfig config) {
        return configMapper.exists(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, config.getConfigKey())
                .ne(ObjectUtil.isNotNull(config.getConfigId()), SysConfig::getConfigId, config.getConfigId()));
    }

    /**
     * 查询验证码开关
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        return selectCaptchaEnabledPublic();
    }

    /**
     * 设置cache key
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

    private LambdaQueryWrapper<SysConfig> buildQueryWrapper(SysConfig query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<SysConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(query.getConfigName()), SysConfig::getConfigName, query.getConfigName());
        lqw.like(StrUtil.isNotBlank(query.getConfigKey()), SysConfig::getConfigKey, query.getConfigKey());
        lqw.like(StrUtil.isNotBlank(query.getConfigType()), SysConfig::getConfigType, query.getConfigType());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByAsc(SysConfig::getCreateTime);
        return lqw;
    }

    /**
     * 查询参数键值
     * @param configKey 参数键名
     * @return 参数键值
     */
    @Override
    public String selectConfigByKeyForApi(String configKey) {
        return selectConfigByKeyPublic(configKey);
    }

    /**
     * 查询验证码开关
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabledForApi() {
        return selectCaptchaEnabledPublic();
    }

    /**
     * 查询参数键值
     * @param configKey 参数键名
     * @return 参数键值
     */
    public String selectConfigByKeyPublic(String configKey) {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig sysConfig = configMapper.selectOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, configKey));
        if (StringUtils.isNotNull(sysConfig)) {
            redisService.setCacheObject(getCacheKey(configKey), sysConfig.getConfigValue());
            return sysConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 查询验证码开关
     * @return true开启，false关闭
     */
    public boolean selectCaptchaEnabledPublic() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }
}
